package com.zbkj.client.service.impl;

import com.zbkj.client.service.ClientProductService;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.assets.ClientProduct;
import com.zbkj.client.dao.ClientProductMapper;
import com.zbkj.common.model.assets.Knowledge;
import com.zbkj.common.model.assets.Material;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.zbkj.common.vo.client.CreateFolderVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zbkj.common.request.client.ClientProductAddRequest;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.common.vo.client.OssResponseVo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;

@Slf4j
@Service
public class ClientProductServiceImpl implements ClientProductService {

    @Autowired
    private ClientProductMapper clientProductMapper;
    
    private ObjectMapper objectMapper = new ObjectMapper();


    private List<String> delProduct(Integer id, List<String> fileList) {
        ClientProduct product = clientProductMapper.selectById(id);
        if (product == null) throw new RuntimeException("产品不存在");
        // 判断是否为文件夹
        if (product.getIsFolder() != null && product.getIsFolder() == 1) {
            // 文件夹，删除所有子项
            String delFolderId = product.getCompleteFolder() + id + "/";
            UpdateWrapper<ClientProduct> updateWrapper = new UpdateWrapper<>();
            updateWrapper.likeRight("complete_folder", delFolderId);

            // 添加符合条件的is_folder=0记录的id到fileList
            List<ClientProduct> childItems = clientProductMapper.selectList(updateWrapper);
            for (ClientProduct childItem : childItems) {
                if (childItem.getIsFolder() != null && childItem.getIsFolder() == 0) {
                    if (childItem.getUrl() != null && !childItem.getUrl().isEmpty()) {
//                        fileList.add(childItem.getUrl());
                    }
                }
            }

            updateWrapper.set("is_del", 1);
            clientProductMapper.update(null, updateWrapper);
        }else{
            if (product.getUrl() != null && !product.getUrl().isEmpty()) {
//                fileList.add(product.getUrl());
            }
        }

        // 删除自身
        product.setIsDel(1);
        product.setUpdateTime(new Date());
        clientProductMapper.deleteById(product);
        return fileList;
    }

    @Override
    public boolean batchDelProduct(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        //要批量删除OSS文件，减少OSS删除文件的请求
        List<String> fileList = new ArrayList<>();
        
        for (Integer id : ids) {
            try {
                List<String> result = delProduct(id, fileList);
                fileList = result;
            } catch (Exception e) {
                // 记录错误但继续处理其他ID
                System.err.println("删除产品ID " + id + " 失败: " + e.getMessage());
            }
        }

        //这里调用OSS的批量删除接口
        log.info("要删除的文件为：{}", fileList);
        // 如果列表不为空，异步删除OSS文件
        if (!fileList.isEmpty()) {
            final List<String> finalFileList = fileList;
            CompletableFuture.runAsync(() -> {
                try {
                    OssUtil.deleteMultiFileFromUrls(finalFileList);
                    log.info("异步删除OSS文件成功: {}", finalFileList);
                } catch (Exception e) {
                    log.error("异步删除OSS文件失败: {}, 错误信息: {}", finalFileList, e.getMessage());
                }
            });
        }

        return true;
    }

    @Override
    public boolean createFolderOrMove(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        Integer merId = vo.getMerId();
        Integer parentId = vo.getParentId();
        String name = vo.getName();
        Integer id = vo.getId();
        // 重命名
        if (name != null && !name.isEmpty() && id != null) {
            ClientProduct product = clientProductMapper.selectById(id);
            if (product == null) throw new RuntimeException("要重命名的文件夹不存在");
            if (product.getUserId() != userId) throw new CrmebException("您无权进行该操作");

            product.setName(name);
            product.setUpdateTime(new java.util.Date());
            clientProductMapper.updateById(product);
            return true;
        }
        // 移动
        if ((name == null || name.isEmpty()) && parentId != null && id != null) {
            ClientProduct folder = clientProductMapper.selectById(id);
            if (folder == null) throw new RuntimeException("要移动的文件夹不存在");
            if (folder.getUserId() != userId) throw new CrmebException("您无权进行该操作");

            String completeFolderOld = folder.getCompleteFolder();
            String oldPath = completeFolderOld + id + "/";
            ClientProduct parent = clientProductMapper.selectById(parentId);
            if (parent == null) throw new RuntimeException("目标父级文件夹不存在");

            if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");
            if (parent.getIsFolder() == 0) throw new CrmebException("请对文件夹进行操作");

            String completeFolderNew = parent.getCompleteFolder() + parent.getId() + "/";

            if (folder.getIsFolder() == 1){
                // 只有原文件是文件夹类型，才更新所有子文件夹和文件的complete_folder
                UpdateWrapper<ClientProduct> updateWrapper = new UpdateWrapper<>();
                updateWrapper.likeRight("complete_folder", oldPath);
                updateWrapper.setSql("complete_folder = CONCAT('" + completeFolderNew + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
                clientProductMapper.update(null, updateWrapper);
            }

            folder.setParentId(parentId);
            folder.setCompleteFolder(completeFolderNew);
            folder.setUpdateTime(new java.util.Date());
            clientProductMapper.updateById(folder);
            return true;
        }
        // 新建
        if (id == null) {
            ClientProduct product = new ClientProduct();
            product.setName(name);
            product.setParentId(parentId);
            product.setIsFolder(1);
            product.setIsDel(0);
            product.setIsShare(0);
            product.setUserId(userId);
            product.setMerId(merId);
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            String completeFolder = "/";
            if (parentId != null && parentId != 0) {
                ClientProduct parent = clientProductMapper.selectById(parentId);
                if (parent == null) throw new RuntimeException("父级文件夹不存在");
                if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");

                completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
            }
            product.setCompleteFolder(completeFolder);
            clientProductMapper.insert(product);
            return true;
        }
        return false;
    }

    @Override
    public boolean createFolder(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        Integer merId = vo.getMerId();
        Integer parentId = vo.getParentId();
        String name = vo.getName();

        //拼接对象
        ClientProduct product = new ClientProduct();
        product.setName(name);
        product.setParentId(parentId);
        product.setIsFolder(1);
        product.setIsDel(0);
        product.setIsShare(0);
        product.setUserId(userId);
        product.setMerId(merId);
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());

        String completeFolder = "/";
        if (parentId != null && parentId != 0) {
            ClientProduct parent = clientProductMapper.selectById(parentId);
            if (parent == null) throw new RuntimeException("父级文件夹不存在");
            if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");
            if (parent.getIsFolder() == 0) throw new CrmebException("不能移动到非文件夹下");

            completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
        }
        product.setCompleteFolder(completeFolder);
        clientProductMapper.insert(product);
        return true;
    }

    @Override
    public boolean renameFile(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        String name = vo.getName();
        Integer id = vo.getId();

        if(name == null || name.isEmpty()) throw new CrmebException("请输入要改的名字");
        if(id == null || id == 0) throw new CrmebException("请选择要改名的文件");

        ClientProduct product = clientProductMapper.selectById(id);
        if (product == null) throw new RuntimeException("请选择存在的文件进行操作");
        if (product.getUserId() != userId) throw new CrmebException("您无权进行该操作");

        product.setId(id);
        product.setName(name);
        product.setUpdateTime(new Date());
        clientProductMapper.updateById(product);
        return true;
    }

    @Override
    public boolean moveFolder(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        Integer parentId = vo.getParentId();
        Integer id = vo.getId();

        // 移动文件夹：name为空且parentId不为空且id不为空
        if(id == null) throw new CrmebException("请选择要移动的文件或者文件夹");

        ClientProduct folder = clientProductMapper.selectById(id);
        if (folder == null) throw new CrmebException("要移动的文件夹不存在");
        //TODO 2
        if (folder.getUserId() != userId) throw new CrmebException("您无权进行该操作");

        String completeFolderOld = folder.getCompleteFolder();
        String oldPath = completeFolderOld + id + "/";

        // 新父级
        String completeFolder = "/";
        if (parentId != 0) {
            ClientProduct parent = clientProductMapper.selectById(parentId);
            if (parent == null) throw new CrmebException("父级文件夹不存在");

            if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");
            if (parent.getIsFolder() == 0) throw new CrmebException("请对文件夹进行操作");

            completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
        }

        //TODO 3
        if (folder.getIsFolder() == 1){
            // 只有原文件是文件夹类型，才更新所有子文件夹和文件的complete_folder
            UpdateWrapper<ClientProduct> updateWrapper = new UpdateWrapper<>();
            updateWrapper.likeRight("complete_folder", oldPath);
            updateWrapper.setSql("complete_folder = CONCAT('" + completeFolder + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
            clientProductMapper.update(null, updateWrapper);
        }
        // 同时更新当前文件夹的parentId和complete_folder
        folder.setParentId(parentId);
        folder.setCompleteFolder(completeFolder);
        folder.setUpdateTime(new Date());
        clientProductMapper.updateById(folder);
        return true;
    }


    @Override
    public List<ClientProduct> listProduct(Integer userId, Integer parentId) {
        QueryWrapper<ClientProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("is_del", 0);
        if (parentId != null) {
            queryWrapper.eq("parent_id", parentId);
        }
        return clientProductMapper.selectList(queryWrapper);
    }

    @Override
    public ClientProduct addClientProduct(ClientProductAddRequest request, Integer userId, Integer merId) {
        ClientProduct product = new ClientProduct();
        product.setName(request.getName());
        product.setIsFolder(request.getIsFolder());
        product.setIsDel(0);
        product.setIsShare(0);
        product.setParentId(request.getParentId() == null ? 0 : request.getParentId());
        product.setCreateTime(new java.util.Date());
        product.setUpdateTime(new java.util.Date());
        product.setUserId(userId);
        product.setMerId(merId);
        // 处理自定义字段
        try {
            product.setCustomeGroup(request.getCustomeGroup() != null ? objectMapper.writeValueAsString(request.getCustomeGroup()) : null);
            product.setSellingPoint(request.getSellingPoint() != null ? objectMapper.writeValueAsString(request.getSellingPoint()) : null);
            product.setUrl(request.getUrl() != null ? objectMapper.writeValueAsString(request.getUrl()) : null);
        } catch (Exception e) {
            throw new CrmebException("JSON序列化失败: " + e.getMessage());
        }
        product.setPrice(request.getPrice());
        product.setBuyLink(request.getBuyLink());
//        product.setUrl(request.getUrl());
        // 处理completeFolder
        String completeFolder = "/";
        if (product.getParentId() != null && product.getParentId() != 0) {
            ClientProduct parent = clientProductMapper.selectById(product.getParentId());
            if (parent != null) {
                completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
            }
        }
        product.setCompleteFolder(completeFolder);

        // 确保isFolder字段正确设置
        if (request.getIsFolder() != null && request.getIsFolder() == 1) {
            product.setIsFolder(1);
        } else {
            product.setIsFolder(0);
        }

        // 插入数据并返回
        clientProductMapper.insert(product);
        return product;
    }

    @Override
    public ClientProduct getById(Integer id) {
        return clientProductMapper.selectById(id);
    }

    @Override
    public boolean editProduct(ClientProductAddRequest request, Integer userId) {
        if (request.getId() == null) {
            throw new CrmebException("产品ID不能为空");
        }
        
        // 获取原产品信息
        ClientProduct product = clientProductMapper.selectById(request.getId());
        if (product == null) {
            throw new CrmebException("产品不存在");
        }
        
        if (!userId.equals(product.getUserId())) {
            throw new CrmebException("无权编辑该产品");
        }
        
        if (product.getIsDel() == null || product.getIsDel() != 0) {
            throw new CrmebException("产品已被删除");
        }
        
        // 更新指定字段
        if (request.getName() != null) {
            product.setName(request.getName());
        }
        
        // 处理自定义字段
        try {
            if (request.getCustomeGroup() != null) {
                product.setCustomeGroup(objectMapper.writeValueAsString(request.getCustomeGroup()));
            }
            if (request.getSellingPoint() != null) {
                product.setSellingPoint(objectMapper.writeValueAsString(request.getSellingPoint()));
            }
            if (request.getUrl() != null) {
                product.setUrl(objectMapper.writeValueAsString(request.getUrl()));
            }
        } catch (Exception e) {
            throw new CrmebException("JSON序列化失败: " + e.getMessage());
        }
        
        if (request.getPrice() != null) {
            product.setPrice(request.getPrice());
        }
        
        if (request.getBuyLink() != null) {
            product.setBuyLink(request.getBuyLink());
        }
        
        // 更新修改时间
        product.setUpdateTime(new Date());
        
        // 保存更新
        int result = clientProductMapper.updateById(product);
        return result > 0;
    }

    @Override
    public boolean batchMoveFolder(CreateFolderVo vo) {
        List<Integer> ids = vo.getIds();
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        
        Integer userId = vo.getUserId();
        Integer parentId = vo.getParentId();
        
        // 验证目标父级文件夹
        if (parentId != null && parentId != 0) {
            ClientProduct parent = clientProductMapper.selectById(parentId);
            if (parent == null) {
                throw new CrmebException("目标父级文件夹不存在");
            }
            if (!userId.equals(parent.getUserId())) {
                throw new CrmebException("无权操作目标文件夹");
            }
            if (parent.getIsFolder() == null || parent.getIsFolder() == 0) {
                throw new CrmebException("目标必须是文件夹");
            }
        }
        
        String completeFolderNew = "/";
        if (parentId != null && parentId != 0) {
            ClientProduct parent = clientProductMapper.selectById(parentId);
            completeFolderNew = parent.getCompleteFolder() + parent.getId() + "/";
        }
        
        for (Integer id : ids) {
            try {
                ClientProduct folder = clientProductMapper.selectById(id);
                if (folder == null) {
                    throw new CrmebException("文件夹ID " + id + " 不存在");
                }
                if (!userId.equals(folder.getUserId())) {
                    throw new CrmebException("无权操作文件夹ID " + id);
                }

                
                String completeFolderOld = folder.getCompleteFolder();
                String oldPath = completeFolderOld + id + "/";

                if (folder.getIsFolder() == 1){
                    // 更新所有子文件夹和文件的complete_folder
                    UpdateWrapper<ClientProduct> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.likeRight("complete_folder", oldPath);
                    updateWrapper.setSql("complete_folder = CONCAT('" + completeFolderNew + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
                    clientProductMapper.update(null, updateWrapper);
                }
                
                // 更新当前文件夹
                folder.setParentId(parentId);
                folder.setCompleteFolder(completeFolderNew);
                folder.setUpdateTime(new Date());
                clientProductMapper.updateById(folder);
                
            } catch (Exception e) {
                throw new CrmebException("移动文件夹ID " + id + " 失败: " + e.getMessage());
            }
        }
        
        return true;
    }

    @Override
    public Integer countProductByUserId(Integer userId) {
        QueryWrapper<ClientProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0)
                   .eq("is_folder", 0)
                   .eq("user_id", userId);
        return clientProductMapper.selectCount(queryWrapper);
    }

} 